const express = require('express');
const router = express.Router();
const Club = require('../../models/clubsModels/create') ;

// 获取所有社团信息
router.get('/allClubs', async (req, res) => {
  try {
    // 查询所有社团，按创建时间降序排列
    const clubs = await Club.findAll({
      order: [['created_at', 'DESC']]
    });

    // 格式化日期字段（如果需要）
    const formattedClubs = clubs.map(club => {
      return {
        ...club.get({ plain: true }),
        created_at: club.created_at.toISOString().split('T')[0] // 格式化为 YYYY-MM-DD
      };
    });

    res.status(200).json({
      success: true,
      data: formattedClubs
    });
  } catch (error) {
    console.error('获取社团列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取社团列表失败'
    });
  }
});

// 根据社长查找社团
router.get('/president/:president', async (req, res) => {
  try {
    const { president } = req.params;
    const clubs = await Club.findAll({
      where: { president },
      attributes: ['id', 'name', 'description', 'type', 'president', 'created_at']
    });
    res.json({
      success: true,
      data: clubs
    });
  } catch (error) {
    console.error('查找社团失败:', error);
    res.status(500).json({
      success: false,
      message: '查找社团失败'
    });
  }
});

// 根据社团ID获取社团信息
router.get('/club/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const club = await Club.findByPk(id, {
      attributes: ['id', 'name', 'description', 'type', 'president', 'created_at']
    });
    
    if (!club) {
      return res.status(404).json({
        success: false,
        message: '未找到该社团'
      });
    }

    res.json({
      success: true,
      data: club
    });
  } catch (error) {
    console.error('获取社团信息失败:', error);
    res.status(500).json({
      success: false,
      message: '获取社团信息失败'
    });
  }
});

module.exports = router;